<?php

/**
 * 
 * @desc This class defines object models of database tables with validation support
 * @see http://code.google.com/p/dabase
 * @author Barbushin Sergey http://www.linkedin.com/in/barbushin
 * 
 */
class DaBase_Object extends DaBase_Model {
	
	public $id;
	
	const table = null;
	const validateOnInsert = true;
	const validateOnUpdate = true;

	public function __construct(array $properties = array(), DaBase_Getter $getter) {
		$this->getter($getter);
		parent::__construct($properties);
	}

	public function getter(DaBase_Getter $setGetter = null) {
		static $getter;
		if ($setGetter) {
			$getter = $setGetter;
		}
		if (!$getter) {
			throw new DaBase_Exception('Getter is not defined');
		}
		return $getter;
	}
	
	/**************************************************************
	 CRUD
	 **************************************************************/
	
	public function insert() {
		if ($this->id) {
			throw new Exception('Trying to make insert() of object with not empty "id"');
		}
		$this->validateOnInsert();
		$this->getter()->getDb()->query('INSERT INTO # SET ,=', $this->getter()->getTable(), $this->asArray(true, true));
		$this->id = $this->getter()->getDb()->getLastInsertId($this);
		return $this;
	}

	public function update() {
		if (!$this->id) {
			throw new Exception('Trying to make update() of object with empty "id"');
		}
		$this->validateOnUpdate();
		$this->getter()->getDb()->query('UPDATE # SET ,= WHERE #=?', $this->getter()->getTable(), $this->asArray(true, true), 'id', $this->id);
		return $this;
	}

	public function delete() {
		$this->getter()->getDb()->query('DELETE FROM # WHERE #=?', $this->getter()->getTable(), 'id', $this->id);
		$this->id = null;
		return $this;
	}

	/**************************************************************
	 VALIDATION
	 **************************************************************/
	
	protected function validateOnInsert() {
		if (self::validateOnInsert !== false) {
			$this->validate(self::validateOnInsert);
		}
	}

	protected function validateOnUpdate() {
		if (self::validateOnUpdate !== false) {
			$this->validate(self::validateOnUpdate);
		}
	}

	/**************************************************************
	 MAGICS
	 **************************************************************/
	
	public function __clone() {
		$clone = clone $this;
		$clone->id = null;
		return $clone;
	}

	public function __toString() {
		return $this->id;
	}
}